package top.itaso.app

import android.Manifest
import android.app.AlertDialog
import android.content.DialogInterface
import android.graphics.Outline
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.Menu
import android.view.View
import android.view.ViewOutlineProvider
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.Navigation
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import com.permissionx.guolindev.PermissionX
import top.itaso.app.MainDrawerActivity
import top.itaso.app.databinding.ActivityMainDrawerBinding
import top.itaso.lib.alog.ALog
import top.itaso.lib.common.AppUtils
import top.itaso.lib.common.ToastUtils
import java.util.*

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
class MainDrawerActivity : AppCompatActivity() {
    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainDrawerBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ALog.vTag(TAG, "savedInstanceState: %s", savedInstanceState)
        binding = ActivityMainDrawerBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.appBarMainDrawer.toolbar)

        binding.appBarMainDrawer.fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }
        val drawerLayout = binding.drawerLayout
        val navView = binding.navView
        initHeadView(navView)

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.nav_home, R.id.nav_demo, R.id.nav_gallery, R.id.nav_slideshow
            ), drawerLayout
        )
        val navController =
            Navigation.findNavController(this, R.id.nav_host_fragment_content_main_drawer)
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)

        PermissionX.init(this)
            .permissions(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            .request { allGranted, grantedList, deniedList ->
                ALog.dTag(
                    TAG,
                    "grantedList:${
                        grantedList.toTypedArray().contentToString()
                    },deniedList:${deniedList.toTypedArray().contentToString()}"
                )
                if (!allGranted) {
                    Toast.makeText(this, "请到设置中打开存储权限，确保功能可用", Toast.LENGTH_LONG).show()
                }
            }
    }

    /**
     * 实例 Drawer 的 HeaderView 视图
     * Spanned.SPAN_INCLUSIVE_EXCLUSIVE: INCLUSIVE-闭区间，EXCLUSIVE-开区间，所以该属性为 闭开区间[start,end)
     *
     * @param navigationView
     */
    private fun initHeadView(navigationView: NavigationView) {
        ALog.dTag(TAG, "headerCount:%s", navigationView.headerCount)
        val headerView = navigationView.getHeaderView(0) //获取头布局

        val layoutFooter = headerView.findViewById<View>(R.id.layout_footer_drawer_header)
        layoutFooter.findViewById<View>(R.id.tv_bluetooth_item).setOnClickListener(
            View.OnClickListener {
                ToastUtils.getInstance().showShortToast(this@MainDrawerActivity, "蓝牙")
            })
        layoutFooter.findViewById<View>(R.id.tv_tv_item)
            .setOnClickListener {
                ToastUtils.getInstance().showShortToast(this@MainDrawerActivity, "TV")
            }
        layoutFooter.findViewById<View>(R.id.tv_phone_item)
            .setOnClickListener(object : View.OnClickListener {
                override fun onClick(view: View) {
                    ToastUtils.getInstance().showShortToast(this@MainDrawerActivity, "电话")
                }
            })
        layoutFooter.findViewById<View>(R.id.tv_ipad_item)
            .setOnClickListener(object : View.OnClickListener {
                override fun onClick(view: View) {
                    ToastUtils.getInstance().showShortToast(this@MainDrawerActivity, "平板")
                }
            })

        val ivAvatar = headerView.findViewById<ImageView>(R.id.iv_avatar)
        ivAvatar.outlineProvider = object : ViewOutlineProvider() {
            override fun getOutline(view: View, outline: Outline) {
                outline.setRoundRect(
                    0,
                    0,
                    view.width,
                    view.height,
                    (resources.getDimensionPixelSize(R.dimen.dimen_radius_middle) * 2).toFloat()
                )
            }
        }
        ivAvatar.clipToOutline = true //圆角裁剪
        val tvDisplayName = headerView.findViewById<TextView>(R.id.tv_display_name)
        tvDisplayName.text = "itaso"

        val tvCurVersionName = headerView.findViewById<TextView>(R.id.tv_version_name)
        val curVersionName = getString(
            R.string.tip_cur_version,
            AppUtils.getAppVersionName(this, null),
            AppUtils.getVersionCode(this, null).toString()
        )
        //        final String curVersionName = String.format(getString(R.string.tip_cur_version), AppUtils.getAppVersionName(this, null), String.valueOf(AppUtils.getVersionCode(this, null)));
        val spanVersionName = SpannableString(curVersionName)
        val fgColorVersionName = ForegroundColorSpan(resources.getColor(R.color.color_4169E1))
        spanVersionName.setSpan(
            fgColorVersionName,
            5,
            curVersionName.length,
            Spanned.SPAN_INCLUSIVE_EXCLUSIVE
        )
        tvCurVersionName.text = spanVersionName
    }

    override fun onStart() {
        ALog.vTag(TAG, "......")
        super.onStart()
    }

    override fun onRestart() {
        ALog.vTag(TAG, "......")
        super.onRestart()
    }

    override fun onResume() {
        ALog.vTag(TAG, "......")
        super.onResume()
    }

    override fun onPause() {
        ALog.vTag(TAG, "......")
        super.onPause()
    }

    override fun onStop() {
        ALog.vTag(TAG, "......")
        super.onStop()
    }

    override fun onDestroy() {
        ALog.vTag(TAG, "......")
        super.onDestroy()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        ALog.vTag(TAG, "......")
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main_drawer, menu)
        return true
    }

    override fun onSupportNavigateUp(): Boolean {
        ALog.vTag(TAG, "......")
        val navController =
            Navigation.findNavController(this, R.id.nav_host_fragment_content_main_drawer)
        return (NavigationUI.navigateUp(navController, (appBarConfiguration)!!)
                || super.onSupportNavigateUp())
    }

    override fun onBackPressed() {
        ALog.vTag(TAG, "......")
        exitApp()
    }

    private fun exitApp() {
        val builder = AlertDialog.Builder(this)
        builder.setMessage("确定要退出吗?")
        builder.setTitle("提示")
        builder.setPositiveButton("确认") { dialog, which ->
            dialog.dismiss()
            Process.killProcess(Process.myPid())
        }
        builder.setNegativeButton("取消",
            object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface, which: Int) {
                    dialog.dismiss()
                }
            })
        builder.create().show()
    }

    companion object {
        private val TAG = MainDrawerActivity::class.java.simpleName
    }
}